import React, {Component} from 'react';
import GridTable from '../components/display/gridTable';
import ScModal from '../components/feedback/scModal';
import { Button, Input } from 'antd';
import Transfer from 'antd/lib/transfer';
import {
    getRoleList,
    getPermissionList,
    editRole,
    deleteRole, getUserMenuList
} from '../fetch/fetchApi';
import '../assets/stylus/com/dataentry/transfer.styl';
import PropTypes from "prop-types";

class Home extends Component {
    constructor () {
        super();
        this.init();
        this.state = {
            gridData: null,
            modalVisible: !1,
            modalTitle: '',
            fromData: [],
            defaultTarget: [],
            confirmLoading: !1,
            inputValue: '',
            loading: !1,
            defaultTitle: '',
            defaultType: undefined,
            pagination: {
                current: 1,
                defaultCurrent: 1,
                defaultPageSize: 10,
                onChange: this.tableChange.bind(this)
            }
        }
    }

    static contextTypes = {
        router: PropTypes.object.isRequired
    }

    tableChange (e) {
        const page = {...this.state.pagination};
        page.current = e;
        this.setState({
            pagination: page
        });
    }

    init () {
        this.title = '角色管理';
        this.subTitle = '角色列表';
        this.selectedKey = ['000202'];
        this.openKeys = ['00', '0002'];
        this.tableColumns = [
            {
                title: '角色名称',
                dataIndex: 'title',
                key: 'title',
            },
            {
                title: '操作',
                key: 'action',
                render: (text, record) => (
                    <div className="action-wrap">
                        <Button type="danger" id={record.key} onClick={this.deleteRole.bind(this)}>删除</Button>
                        <Button type="primary"
                                id={record.key}
                                title="编辑角色"
                                deftitle={record.title}
                                detarget = {record.paramStr}
                                onClick={this.openNewRole.bind(this)}>编辑</Button>
                    </div>
                )
            }
        ];
    }

    componentWillMount () {
        this.params = {};
        this.getRoleListCb();
        this.getPermissionList();
        this.getUserMenuList();
    }

    getRoleListCb () {
      this.getRoleList().then(() => {
        this.setState({
          loading: !1
        });
      });
    }

    async getUserMenuList () {
        try {
            const resData = await getUserMenuList();
            this.setState({
                'menuList': resData.data.data
            })
        } catch (e) {
            console.log(e);
        }
    }

    async getRoleList () {
          this.setState({
            loading: !0
          });
        try {
            const resData = await getRoleList();
            let gridData = resData.data.data;
            for (let i of gridData) {
                i.type === 1 && (i.info = '菜单读权限');
                i.type === 2 && (i.info = '菜单写权限');
                i.type === 3 && (i.info = '数据城市查询权限');
            }
            const page = {...this.state.pagination};
            page.total = gridData.length;
            this.setState({
                modalVisible: !1,
                gridData,
                pagination: page
            });
        } catch (e) {
            console.log(e);
        }
    }

    async getPermissionList () {
        try {
            const resData = await getPermissionList();
            const formatBeforeData = resData.data.data;
            const fromData = JSON.parse(JSON.stringify(formatBeforeData).replace(/id/g,'key').replace(/childList/g, 'children'));
            this.setState({
                fromData
            });
        } catch (e) {
            console.log(e);
        }
    }

    openNewRole (e) {
        this.setState({
            modalVisible: !0,
            modalTitle: e.target.title,
            roleId: e.target.id,
            defaultTitle: e.target.getAttribute('deftitle'),
            defaultTarget: e.target.getAttribute('detarget') && e.target.getAttribute('detarget').split(',') || undefined
        });
        this.params = {
            roleId: e.target.id || null,
            title: e.target.getAttribute('deftitle'),
            permissionIds: e.target.getAttribute('detarget')
        };
    }

    async editRole (params) {
        this.setState({
          confirmLoading: !0
        });
        try {
            const param = params;
            const resData = await editRole(param);
              this.setState({
                confirmLoading: !1
              });
            resData.data.code === '200' && this.getRoleListCb();
        } catch (e) {
            console.log(e);
        }
    }

    async deleteRole (e) {
        try {
            const param = {id: e.target.id};
            const resData = await deleteRole(param);
            resData.data.code === '200' && this.getRoleListCb();
        } catch (e) {
            console.log(e);
        }
    }

    setInputVale (e) {
        this.params.title = e.target.value;
        this.setState({
            defaultTitle: e.target.value
        });
    }

    handleTransferChange (target) {
        this.setState({
            defaultTarget: target
        });
        console.log(target.join(','));
        this.params.permissionIds = target.join(',');
    }

    filterOption (inputValue, option) {
        return option.description.indexOf(inputValue) > -1;
    }

    cancel () {
        this.setState({
            modalVisible: !1
        });
    }

    render () {
        const Content = <div className="sc-page-content">
            <div className="page-toolbar">
                <Button type="primary"
                        title="新增角色"
                        deftitle=""
                        deftype = ""
                        onClick={this.openNewRole.bind(this)}>新增</Button>
            </div>
            <div className="page-panel">
                <GridTable postyle="table-center" data={this.state.gridData} loading={this.state.loading} columns={this.tableColumns} pagination={this.state.pagination}/>
            </div>
        </div>;
        return <div>
            {Content}
            <ScModal
                modalVisible={this.state.modalVisible}
                modalTitle={this.state.modalTitle}
                modalContent={<div>
                    <div className="modal-list">
                        <Input placeholder="请输入角色名称" value={this.state.defaultTitle} onChange={this.setInputVale.bind(this)} />
                    </div>
                    <div className="modal-list">
                        <Transfer
                            dataSource={this.state.fromData}
                            showSearch
                            titles={['所有权限', '已选权限']}
                            searchPlaceholder="请输入权限"
                            notFoundContent="暂无权限数据"
                            itemUnit="条"
                            targetKeys={this.state.defaultTarget}
                            onChange={this.handleTransferChange.bind(this)}
                            render={item => item.title}
                        />
                    </div>
                </div>}
                handle = {this.editRole.bind(this)}
                cancel = {this.cancel.bind(this)}
                confirmLoading={this.state.confirmLoading}
                param = {this.params}
            />
        </div>
    }
}

export default Home;